#include "music_component.h"
#include "ui_music_component.h"
#include <QDesktopServices>
#include <QDebug>

#include <QSslConfiguration>
#include <QSslSocket>
#include <QSslError>

#include <QEvent>  // 事件头文件
#include <QCursor> // 光标头文件


MusicComponent::MusicComponent(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MusicComponent)
    , songListInterface(nullptr)
    , lyricsInterface(nullptr)
    , currentPlayIndex(-1)
    , isDefaultPlaylistMode(false)
    , currentSearchIndex(-1)
{
    ui->setupUi(this);

    // 初始化媒体播放器
    Media = new QMediaPlayer(this);

    // 初始化网络请求管理器
    manager = new QNetworkAccessManager(this);

    // 初始化堆叠窗口
    stackedWidget = new QStackedWidget(this);

    // 确保widget_3有合适的大小策略
    ui->widget_3->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 将widget_3添加到堆叠窗口作为第一页（主界面）
    stackedWidget->addWidget(ui->widget_3);

    // 初始化歌词界面并添加到堆叠窗口作为第二页
    lyricsInterface = new Lyrics_interface();
    lyricsInterface->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    lyricsInterface->setMediaPlayer(Media);  // 设置媒体播放器
    stackedWidget->addWidget(lyricsInterface);

    // 使用现有布局而不是创建新布局
    QLayout* existingLayout = this->layout();
    if (existingLayout) {
        // 清空现有布局的所有内容
        QLayoutItem* child;
        while ((child = existingLayout->takeAt(0)) != nullptr) {
            if (child->widget()) {
                child->widget()->setParent(nullptr);
            }
            delete child;
        }
        // 添加堆叠窗口到现有布局
        existingLayout->addWidget(stackedWidget);
    }

    // 初始化歌单详情界面 - 确保正确的初始状态
    songListInterface = new song_list_interface(this);
    songListInterface->hide(); // 初始隐藏
    // 明确设置父对象
    songListInterface->setParent(this);

    // 初始隐藏widget和widget_2
    ui->widget->hide();    // 搜索结果列表
    ui->widget_2->hide();  // 歌单按钮组

    // 安装事件过滤器
    this->installEventFilter(this);

    // 连接按钮信号
    connect(ui->pushButton_2, &QPushButton::clicked, this, &MusicComponent::searchMusic);//搜索按钮连接
    connect(ui->listWidget, &QListWidget::itemClicked, this, &MusicComponent::onItemClicked);
    connect(ui->pushButton, &QPushButton::clicked, this, &MusicComponent::playMusic);//播放按钮连接
    connect(ui->pushButton_8, &QPushButton::clicked, this, &MusicComponent::pauseMusic);//暂停按钮连接
    connect(ui->pushButton_3, &QPushButton::clicked, this, &MusicComponent::onPlaylistButtonClicked);//歌单按钮连接
    // 连接歌单管理按钮信号
    connect(ui->pushButton_4, &QPushButton::clicked, this, &MusicComponent::onCreatePlaylist);
    connect(ui->pushButton_5, &QPushButton::clicked, this, &MusicComponent::onDeletePlaylist);
    connect(ui->listWidget_2, &QListWidget::itemClicked, this, &MusicComponent::onPlaylistItemClicked);
    connect(ui->listWidget_2, &QListWidget::itemDoubleClicked, this, &MusicComponent::onPlaylistItemDoubleClicked);
    // 连接歌单界面的返回信号
    connect(songListInterface, &song_list_interface::backToPlaylist, this, &MusicComponent::onBackFromSongList);
    // 连接歌词按钮信号
    connect(ui->pushButton_7, &QPushButton::clicked, this, &MusicComponent::showLyricsInterface);
    // 连接歌词界面的返回信号
    connect(lyricsInterface, &Lyrics_interface::backToMain, this, &MusicComponent::backToMainInterface);
    // 连接歌词界面的添加歌曲到歌单信号
    connect(lyricsInterface, &Lyrics_interface::addSongToPlaylistRequested,this, &MusicComponent::onAddSongToPlaylistRequested);
    // 连接歌单界面的信号
    connect(songListInterface, &song_list_interface::backToPlaylist, this, &MusicComponent::onBackFromSongList);
    connect(songListInterface, &song_list_interface::songDoubleClicked, this, &MusicComponent::onSongDoubleClickedFromPlaylist);
    connect(songListInterface, &song_list_interface::deleteSongRequested, this, &MusicComponent::onDeleteSongFromPlaylist);
    // 连接歌词界面的上一首/下一首信号
        connect(lyricsInterface, &Lyrics_interface::previousSongRequested, this, &MusicComponent::onPreviousSongRequested);
        connect(lyricsInterface, &Lyrics_interface::nextSongRequested, this, &MusicComponent::onNextSongRequested);
        // 连接媒体播放结束信号
           connect(Media, &QMediaPlayer::mediaStatusChanged, this, &MusicComponent::onMediaStatusChanged);


           connect(lyricsInterface, &Lyrics_interface::currentLyricChanged, this, &MusicComponent::updateCurrentLyricDisplay);
    // 确保初始显示主界面
    stackedWidget->setCurrentIndex(0);

    // 加载歌单列表
    loadPlaylists();

    qDebug() << "MusicComponent initialized, stackedWidget has" << stackedWidget->count() << "pages";
    qDebug() << "Current page:" << stackedWidget->currentIndex();

    // 当歌曲开始播放时获取歌词
    connect(Media, &QMediaPlayer::stateChanged, this, [this](QMediaPlayer::State state) {
        if (state == QMediaPlayer::PlayingState && !currentPlayingSongId.isEmpty()) {
            fetchLyrics(); // 播放时获取歌词
        }
    });
    loadDefaultPlaylist();// 确保加载默认歌单
}

MusicComponent::~MusicComponent()
{
    delete ui;
}
// 事件过滤器实现
bool MusicComponent::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress) {
        QWidget *clickedWidget = qobject_cast<QWidget*>(obj);
        if (clickedWidget) {
            // 检查是否点击了歌单按钮或其子部件
            bool clickInPlaylistButton = (clickedWidget == ui->pushButton_3 ||
                                         ui->pushButton_3->isAncestorOf(clickedWidget));

            // 如果点击了歌单按钮，不隐藏widget_2
            if (clickInPlaylistButton) {
                return QWidget::eventFilter(obj, event);
            }

            bool clickInWidget = ui->widget->isVisible() &&
                                (ui->widget->rect().contains(ui->widget->mapFromGlobal(QCursor::pos())) ||
                                 ui->widget->isAncestorOf(clickedWidget));

            bool clickInWidget2 = ui->widget_2->isVisible() &&
                                 (ui->widget_2->rect().contains(ui->widget_2->mapFromGlobal(QCursor::pos())) ||
                                  ui->widget_2->isAncestorOf(clickedWidget));

            bool clickInSearchButton = (clickedWidget == ui->pushButton_2 ||
                                       ui->pushButton_2->isAncestorOf(clickedWidget));

            // 如果点击在widget或widget_2外部，且不是搜索按钮，则隐藏它们
            if (!clickInWidget && !clickInWidget2 && !clickInSearchButton) {
                ui->widget->hide();
                ui->widget_2->hide();
            }
        }
    }
    return QWidget::eventFilter(obj, event);
}
// 更新当前歌词显示到按钮
void MusicComponent::updateCurrentLyricDisplay(const QString& lyric)
{
    if (!lyric.isEmpty() && lyric != "暂无歌词") {
        // 限制歌词长度，避免按钮显示过长
        QString displayText = lyric;
        if (displayText.length() > 15) {
            displayText = displayText.left(15) + "...";
        }
        ui->pushButton_7->setText(displayText);
    } else {
        ui->pushButton_7->setText("歌词");
    }
}
// 处理歌单中歌曲双击 - 进入歌词界面
void MusicComponent::onSongDoubleClickedFromPlaylist()
{
    // 获取当前选中的歌曲
    QListWidgetItem *currentItem = songListInterface->getCurrentSongItem();
    if (!currentItem) {
        QMessageBox::warning(this, "提示", "请先选择一首歌曲！");
        return;
    }

    QString songInfo = currentItem->text();

    // 直接从列表项中获取歌曲ID（UserRole）
    QString songId = currentItem->data(Qt::UserRole).toString();

    if (songId.isEmpty()) {
        // 如果没有存储ID，尝试从搜索列表中匹配
        qDebug() << "No song ID stored, trying to match from search list";
        for (int i = 0; i < ui->listWidget->count(); ++i) {
            QListWidgetItem *item = ui->listWidget->item(i);
            if (item->text() == songInfo) {
                songId = item->data(Qt::UserRole).toString();
                break;
            }
        }
    }

    if (songId.isEmpty()) {
        QMessageBox::warning(this, "提示", "无法找到歌曲ID，请先搜索该歌曲！");
        return;
    }

    // 设置选中的歌曲ID并播放
    selectedSongId = songId;
    currentPlayingSongId = songId;

    qDebug() << "Playing song from playlist:" << songInfo << "ID:" << songId;

    // 播放歌曲
    playMusic();

    // 进入歌词界面
    showLyricsInterface();
}

// 处理删除歌单中的歌曲
void MusicComponent::onDeleteSongFromPlaylist(const QString& songInfo)
{
    if (currentPlaylist.isEmpty()) {
        QMessageBox::warning(this, "错误", "未选择歌单！");
        return;
    }

    // 获取歌单文件路径（确保操作的是可写的本地文件）
    QString filePath = QString("playlists/%1.txt").arg(currentPlaylist);

    // 读取歌单内容，过滤掉要删除的歌曲
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        QStringList songs;
        while (!in.atEnd()) {
            QString line = in.readLine().trimmed();
            if (line.isEmpty()) continue;

            // 分割行内容为「歌曲信息」和「歌曲ID」
            QStringList parts = line.split('|');
            QString storedSongInfo = parts.isEmpty() ? "" : parts[0]; // 取|前面的歌曲信息

            // 只保留不匹配的行（不删除的歌曲）
            if (storedSongInfo != songInfo) {
                songs.append(line);
            }
        }
        file.close();

        // 重新写入过滤后的内容
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream out(&file);
            for (const QString& song : songs) {
                out << song << "\n";
            }
            file.close();
            qDebug() << "Song removed from playlist:" << currentPlaylist << "Song:" << songInfo;
        } else {
            QMessageBox::warning(this, "错误", "无法保存歌单文件！");
        }
    } else {
        QMessageBox::warning(this, "错误", "无法打开歌单文件！路径：" + filePath);
    }
}

// 更新歌词界面的歌单列表
void MusicComponent::updateLyricsPlaylist()
{
    if (!lyricsInterface) return;

    QStringList playlists;
    for (int i = 0; i < ui->listWidget_2->count(); ++i) {
        playlists.append(ui->listWidget_2->item(i)->text());
    }

    // 调用歌词界面的设置歌单函数
    lyricsInterface->setPlaylistItems(playlists);
}
// 处理添加歌曲到歌单请求
void MusicComponent::onAddSongToPlaylistRequested(const QString& playlistName)
{
    if (currentPlayingSongId.isEmpty()) {
        QMessageBox::warning(this, "提示", "没有正在播放的歌曲！");
        return;
    }

    // 获取当前播放的歌曲信息
    QString songInfo;
    for (int i = 0; i < ui->listWidget->count(); ++i) {
        QListWidgetItem *item = ui->listWidget->item(i);
        if (item->data(Qt::UserRole).toString() == currentPlayingSongId) {
            songInfo = item->text();
            break;
        }
    }

    if (songInfo.isEmpty()) {
        QMessageBox::warning(this, "提示", "无法获取歌曲信息！");
        return;
    }

    // 确保playlists目录存在
    QDir dir("playlists");
    if (!dir.exists()) {
        dir.mkpath(".");
    }

    // 检查歌曲是否已在歌单中
    QString filePath = QString("playlists/%1.txt").arg(playlistName);

    QFile checkFile(filePath);
    if (checkFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&checkFile);
        while (!in.atEnd()) {
            QString line = in.readLine().trimmed();
            if (line.contains(currentPlayingSongId)) {
                QMessageBox::warning(this, "提示", "该歌曲已存在于歌单中！");
                checkFile.close();
                return;
            }
        }
        checkFile.close();
    }

    // 添加到歌单 - 格式：歌曲信息|歌曲ID
    QFile file(filePath);
    if (file.open(QIODevice::Append | QIODevice::Text)) {
        QTextStream out(&file);
        out << songInfo << "|" << currentPlayingSongId << "\n";
        file.close();
        QMessageBox::information(this, "提示", QString("歌曲已成功添加到歌单：%1").arg(playlistName));
        qDebug() << "Added song to playlist:" << songInfo << "|" << currentPlayingSongId;
    } else {
        QMessageBox::warning(this, "错误", "无法添加到歌单！文件路径：" + filePath);
        qDebug() << "Failed to open file for writing:" << filePath;
        return;
    }

    // 重新加载歌单列表
    loadPlaylists();
}

// 歌单按钮点击槽函数
void MusicComponent::onPlaylistButtonClicked()
{
    qDebug() << "=== Playlist Button Clicked ===";
    qDebug() << "Stacked widget index:" << stackedWidget->currentIndex();
    qDebug() << "Song list interface visible:" << songListInterface->isVisible();
    qDebug() << "Song list interface parent:" << songListInterface->parent();

    // 如果当前在歌词界面，先返回主界面
    if (stackedWidget->currentIndex() == 1) {
        stackedWidget->setCurrentIndex(0);
    }

    // 如果歌单详情界面正在显示，则返回到歌单列表
    if (songListInterface->isVisible()) {
        qDebug() << "Song list interface is visible, returning to playlist list";
        onBackFromSongList();
        return;
    }

    // 如果widget_2正在显示，则隐藏它
    if (ui->widget_2->isVisible()) {
        ui->widget_2->hide();
        qDebug() << "Hiding widget_2";
    } else {
        // 显示widget_2（歌单列表）
        showPlaylistList();
    }

    qDebug() << "After operation - Widget_2 visible:" << ui->widget_2->isVisible();
}
// 新增辅助函数：显示歌单列表
void MusicComponent::showPlaylistList()
{
    // 确保songListInterface不在widget_2中
    if (songListInterface->parent() == ui->widget_2) {
        songListInterface->setParent(this);
        songListInterface->hide();
    }

    // 恢复widget_2的原始状态
    resetWidget2ToOriginal();

    ui->widget_2->show();
    ui->widget->hide();  // 隐藏搜索结果列表

    // 强制更新界面
    ui->widget_2->raise();
    ui->widget_2->update();

    qDebug() << "Showing widget_2 with playlist list";
}

// 新增辅助函数：重置widget_2到原始状态
void MusicComponent::resetWidget2ToOriginal()
{
    // 如果存在布局，先清除
    if (ui->widget_2->layout()) {
        QLayoutItem* child;
        while ((child = ui->widget_2->layout()->takeAt(0)) != nullptr) {
            delete child;
        }
        delete ui->widget_2->layout();
    }

    // 创建原始布局
    QGridLayout* originalLayout = new QGridLayout(ui->widget_2);
    originalLayout->setContentsMargins(0, 0, 0, 0);
    originalLayout->setSpacing(5);

    // 添加原始控件
    originalLayout->addWidget(ui->listWidget_2, 0, 0);

    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(ui->pushButton_4);
    buttonLayout->addWidget(ui->pushButton_5);
    buttonLayout->addWidget(ui->lineEdit_2);

    originalLayout->addLayout(buttonLayout, 1, 0);
    ui->widget_2->setLayout(originalLayout);

    // 确保控件可见
    ui->listWidget_2->setVisible(true);
    ui->pushButton_4->setVisible(true);
    ui->pushButton_5->setVisible(true);
    ui->lineEdit_2->setVisible(true);
}

// 加载歌单列表
void MusicComponent::loadPlaylists()
{
    ui->listWidget_2->clear();

    qDebug() << "Loading playlists...";

    // 使用本地目录存储歌单
    QDir dir("playlists");
    if (!dir.exists()) {
        qDebug() << "Creating playlists directory...";
        dir.mkpath(".");

        // 创建默认歌单文件
        QStringList defaultPlaylists = {"我的收藏", "最近播放", "流行音乐", "经典老歌"};
        for (const QString &name : defaultPlaylists) {
            QString filePath = QString("playlists/%1.txt").arg(name);
            QFile file(filePath);
            if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
                file.close();
                qDebug() << "Created default playlist:" << name;
            }
        }
    }

    // 查找所有的.txt文件
    QStringList filters;
    filters << "*.txt";
    QFileInfoList files = dir.entryInfoList(filters, QDir::Files);

    qDebug() << "Found" << files.size() << "playlist files";

    for (const QFileInfo &fileInfo : files) {
        QString playlistName = fileInfo.baseName(); // 去掉.txt后缀
        QListWidgetItem *item = new QListWidgetItem(playlistName);
        ui->listWidget_2->addItem(item);
        qDebug() << "Added playlist:" << playlistName;
    }

    qDebug() << "Total playlists loaded:" << ui->listWidget_2->count();
}

// 获取歌单文件路径 - 使用资源文件路径
QString MusicComponent::getPlaylistFilePath(const QString& playlistName)
{
    return QString(":/img/%1.txt").arg(playlistName);
}

// 保存歌单 - 由于资源文件是只读的，需要保存到可写位置
void MusicComponent::savePlaylist(const QString& playlistName, const QString& content)
{
    // 资源文件是只读的，需要保存到可写位置
    QDir dir("playlists"); // 创建本地目录保存歌单
    if (!dir.exists()) {
        dir.mkpath(".");
    }

    QString filePath = QString("playlists/%1.txt").arg(playlistName);
    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&file);
        out << content;
        file.close();
        qDebug() << "Playlist saved to:" << filePath;
    }
}

// 删除歌单文件 - 同样需要修改
void MusicComponent::deletePlaylistFile(const QString& playlistName)
{
    QString filePath = QString("playlists/%1.txt").arg(playlistName);
    QFile file(filePath);
    if (file.exists()) {
        file.remove();
        qDebug() << "Playlist deleted:" << filePath;
    }
}

// 创建歌单
void MusicComponent::onCreatePlaylist()
{
    QString playlistName = ui->lineEdit_2->text().trimmed();
    if (playlistName.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入歌单名称！");
        return;
    }

    // 检查歌单是否已存在
    QString filePath = getPlaylistFilePath(playlistName);
    if (QFile::exists(filePath)) {
        QMessageBox::warning(this, "提示", "歌单已存在！");
        return;
    }

    // 创建空歌单文件
    savePlaylist(playlistName, "");

    // 重新加载歌单列表
    loadPlaylists();

    // 更新歌词界面的歌单列表
    updateLyricsPlaylist();

    ui->lineEdit_2->clear();
}

// 加载用户创建的歌单（从本地目录）
void MusicComponent::loadUserCreatedPlaylists()
{
    QDir dir("playlists");
    if (!dir.exists()) {
        return;
    }

    // 查找所有的.txt文件
    QStringList filters;
    filters << "*.txt";
    QFileInfoList files = dir.entryInfoList(filters, QDir::Files);

    for (const QFileInfo &fileInfo : files) {
        QString playlistName = fileInfo.baseName();
        // 检查是否已经存在同名歌单
        bool exists = false;
        for (int i = 0; i < ui->listWidget_2->count(); ++i) {
            if (ui->listWidget_2->item(i)->text() == playlistName) {
                exists = true;
                break;
            }
        }
        if (!exists) {
            QListWidgetItem *item = new QListWidgetItem(playlistName);
            ui->listWidget_2->addItem(item);
            qDebug() << "Added user playlist:" << playlistName;
        }
    }
}

// 删除歌单
void MusicComponent::onDeletePlaylist()
{
    QListWidgetItem *currentItem = ui->listWidget_2->currentItem();
    if (!currentItem) {
        QMessageBox::warning(this, "提示", "请选择要删除的歌单！");
        return;
    }

    QString playlistName = currentItem->text();

    // 检查是否是预定义歌单（资源文件中的）
    QString resourcePath = getPlaylistFilePath(playlistName);
    if (QFile::exists(resourcePath)) {
        QMessageBox::warning(this, "提示", "预定义歌单不能删除！");
        return;
    }

    int ret = QMessageBox::question(this, "确认删除",
                                   QString("确定要删除歌单\"%1\"吗？").arg(playlistName),
                                   QMessageBox::Yes | QMessageBox::No);

    if (ret == QMessageBox::Yes) {
        deletePlaylistFile(playlistName);

        // 从列表中移除
        delete ui->listWidget_2->takeItem(ui->listWidget_2->row(currentItem));


        // 更新歌词界面的歌单列表
                updateLyricsPlaylist();
    }
}

// 歌单项单击 - 只用于选中，不打开详情
void MusicComponent::onPlaylistItemClicked(QListWidgetItem *item)
{
    if (item) {
        currentPlaylist = item->text();
    }
}
// 双击歌单项 - 显示歌单详情界面在widget_2中
void MusicComponent::onPlaylistItemDoubleClicked(QListWidgetItem *item)
{
    if (item) {
        currentPlaylist = item->text();
        // 隐藏原始歌单控件
        ui->listWidget_2->setVisible(false);
        ui->pushButton_4->setVisible(false);
        ui->pushButton_5->setVisible(false);
        ui->lineEdit_2->setVisible(false);

        // 设置歌单详情界面
        songListInterface->setParent(ui->widget_2);
        songListInterface->setPlaylistName(currentPlaylist);

        // 清除旧布局
        if (ui->widget_2->layout()) {
            QLayoutItem* child;
            while ((child = ui->widget_2->layout()->takeAt(0)) != nullptr) {
                delete child;
            }
            delete ui->widget_2->layout();
        }

        // 新布局
        QVBoxLayout* newLayout = new QVBoxLayout(ui->widget_2);
        newLayout->setContentsMargins(0, 0, 0, 0);
        newLayout->setSpacing(0);
        newLayout->addWidget(songListInterface);
        ui->widget_2->setLayout(newLayout);
        songListInterface->show();

        // 加载歌单内容
        QString filePath;
        QString resourcePath = getPlaylistFilePath(currentPlaylist);
        if (QFile::exists(resourcePath)) {
            filePath = resourcePath;
        } else {
            filePath = QString("playlists/%1.txt").arg(currentPlaylist);
        }

        QFile file(filePath);
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&file);
            QStringList songLines;
            while (!in.atEnd()) {
                QString line = in.readLine().trimmed();
                if (!line.isEmpty()) {
                    songLines.append(line);
                }
            }
            file.close();

            // 清空歌单详情列表
            songListInterface->getListWidget()->clear();

            // 逐行解析并添加到歌单详情列表
            for (const QString& line : songLines) {
                if (line.isEmpty()) continue;

                // 解析格式：歌曲名 - 歌手名|歌曲ID
                QStringList parts = line.split('|');
                if (parts.size() >= 2) {
                    QString songInfo = parts[0]; // 歌曲名 - 歌手名
                    QString songId = parts[1];   // 歌曲ID

                    // 添加到songListInterface的列表，并存储歌曲ID
                    QListWidgetItem* songItem = new QListWidgetItem(songInfo);
                    songItem->setData(Qt::UserRole, songId);
                    songListInterface->getListWidget()->addItem(songItem);
                    qDebug() << "Loaded song:" << songInfo << "ID:" << songId;
                } else {
                    // 处理旧格式（只有歌曲信息，没有ID）
                    qDebug() << "Old format detected:" << line;
                    QListWidgetItem* songItem = new QListWidgetItem(line);
                    songListInterface->getListWidget()->addItem(songItem);
                }
            }
        } else {
            songListInterface->getListWidget()->clear();
            qDebug() << "Cannot open playlist file:" << filePath;
        }
        ui->widget_2->show();
    }
}

// 从歌单界面返回
void MusicComponent::onBackFromSongList()
{
    qDebug() << "开始处理返回操作";

    if (songListInterface) {
        // 先隐藏歌单详情界面
        songListInterface->hide();

        // 重要：确保父对象正确重置
        if (songListInterface->parent() != this) {
            songListInterface->setParent(this);
            qDebug() << "Reset song list interface parent to MusicComponent";
        }

        qDebug() << "Song list interface hidden and parent reset";
    }

    // 恢复widget_2的原始布局和控件
    if (ui->widget_2->layout()) {
        QLayoutItem* child;
        while ((child = ui->widget_2->layout()->takeAt(0)) != nullptr) {
            if (child->widget()) {
                child->widget()->setParent(nullptr);
                child->widget()->hide();
            }
            delete child;
        }
        delete ui->widget_2->layout();
        qDebug() << "Old layout cleared";
    }

    // 重新创建原始布局
    QGridLayout* originalLayout = new QGridLayout(ui->widget_2);
    originalLayout->setContentsMargins(0, 0, 0, 0);
    originalLayout->setSpacing(5);

    // 重新添加原始控件
    originalLayout->addWidget(ui->listWidget_2, 0, 0);

    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(ui->pushButton_4);
    buttonLayout->addWidget(ui->pushButton_5);
    buttonLayout->addWidget(ui->lineEdit_2);

    originalLayout->addLayout(buttonLayout, 1, 0);
    ui->widget_2->setLayout(originalLayout);

    // 显示原始控件
    ui->listWidget_2->setVisible(true);
    ui->pushButton_4->setVisible(true);
    ui->pushButton_5->setVisible(true);
    ui->lineEdit_2->setVisible(true);

    // 确保widget_2显示
    ui->widget_2->show();

    // 确保界面刷新
    ui->widget_2->update();
    this->update();

    qDebug() << "返回操作完成，widget_2 visible:" << ui->widget_2->isVisible();
    qDebug() << "Song list interface parent after return:" << songListInterface->parent();
}
// 搜索音乐函数
void MusicComponent::searchMusic()
{
    QString musicName = ui->lineEdit->text().trimmed();
    if (musicName.isEmpty()) {
        return;
    }
    ui->listWidget->clear();

    // 显示搜索结果列表，隐藏歌单按钮组
    ui->widget->show();
    ui->widget_2->hide();

    // 构造搜索URL
    QString url = QString("http://music.163.com/api/search/get/web?csrf_token=&type=1&s=%1&limit=20").arg(musicName);
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setRawHeader("Referer", "http://music.163.com");
    request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");

    QNetworkReply *reply = manager->get(request);
    connect(reply, &QNetworkReply::finished, this, &MusicComponent::handleSearchReply);
}

//请求返回后，解析 JSON 数据，提取歌曲名、歌手名、歌曲 ID，并显示在QListWidget
void MusicComponent::handleSearchReply() {
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (!reply) return;

    if (reply->error() == QNetworkReply::NoError) {
        QByteArray data = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(data);
        if (!doc.isNull() && doc.isObject()) {
            QJsonObject rootObj = doc.object();
            if (rootObj.contains("result") && rootObj["result"].isObject()) {
                QJsonObject resultObj = rootObj["result"].toObject();
                if (resultObj.contains("songs") && resultObj["songs"].isArray()) {
                    QJsonArray songsArray = resultObj["songs"].toArray();
                    if (songsArray.isEmpty()) {
                        return;
                    }

                    // 清空之前的搜索结果
                    searchResultIds.clear();  // 添加这行
                    ui->listWidget->clear();

                    // 遍历歌曲数组，提取信息并添加到列表
                    for (const QJsonValue &songVal : songsArray) {
                        if (songVal.isObject()) {
                            QJsonObject songObj = songVal.toObject();
                            QString songName = songObj["name"].toString();
                            QString artistName;
                            if (songObj.contains("artists") && songObj["artists"].isArray()) {
                                QJsonArray artistsArray = songObj["artists"].toArray();
                                if (!artistsArray.isEmpty() && artistsArray[0].isObject()) {
                                    artistName = artistsArray[0].toObject()["name"].toString();
                                }
                            }
                            QString songId = QString::number(songObj["id"].toInt());

                            // 在列表中显示"歌曲名 - 歌手名"，并存储歌曲ID
                            QListWidgetItem *item = new QListWidgetItem(QString("%1 - %2").arg(songName).arg(artistName));
                            item->setData(Qt::UserRole, songId);
                            ui->listWidget->addItem(item);
                            searchResultIds.append(songId);  // 添加到搜索结果列表
                        }
                    }
                }
            }
        }
    } else {
    }
    reply->deleteLater();
}

//用户点击列表中的某首歌时，提取其存储的歌曲 ID，供后续播放使用
void MusicComponent::onItemClicked(QListWidgetItem *item) {
    if (item) {
        selectedSongId = item->data(Qt::UserRole).toString();
        // 设置当前搜索索引
        currentSearchIndex = searchResultIds.indexOf(selectedSongId);
    }
}

//获取到歌曲 ID 后，点击"播放"按钮时，可通过网易云的播放链接播放音乐
void MusicComponent::playMusic()
{
    if (selectedSongId.isEmpty()) {
        return;
    }

    // 如果点击的是同一首歌且处于暂停状态，则继续播放
    if (selectedSongId == currentPlayingSongId && Media->state() == QMediaPlayer::PausedState) {
        Media->play();
        qDebug() << "Resuming playback of song ID:" << selectedSongId;
        return;
    }

    // 如果是新歌曲，清空之前的歌词
    if (selectedSongId != currentPlayingSongId) {
        currentLyrics.clear(); // 清空旧歌词
        if (lyricsInterface) {
            lyricsInterface->loadLyrics(""); // 重置歌词界面
        }
    }

    // 使用 HTTP 播放链接
    QString playUrl = QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(selectedSongId);

    // 使用 QMediaPlayer 播放
    Media->setMedia(QUrl(playUrl));
    Media->play();

    // 更新当前播放的歌曲ID
    currentPlayingSongId = selectedSongId;

    qDebug() << "Started playing new song ID:" << selectedSongId;

    // 立即获取新歌词
    fetchLyrics();
}
// 暂停音乐的函数实现
void MusicComponent::pauseMusic()
{
    if (Media->state() == QMediaPlayer::PlayingState) {
        Media->pause();
        qDebug() << "Music paused at position:" << Media->position();
    } else if (Media->state() == QMediaPlayer::PausedState) {
        // 如果已经是暂停状态，再次点击暂停按钮可以继续播放
        Media->play();
        qDebug() << "Resumed playback from pause";
    } else {
        qDebug() << "No music is playing to pause";
    }
}
// 显示歌词界面
void MusicComponent::showLyricsInterface()
{
    qDebug() << "Showing lyrics interface for song:" << currentPlayingSongId;

    // 如果当前没有歌词，但正在播放歌曲，尝试重新获取
    if (currentLyrics.isEmpty() && !currentPlayingSongId.isEmpty()) {
        fetchLyrics();
    }

    // 加载当前歌词到界面
    if (!currentLyrics.isEmpty()) {
        lyricsInterface->loadLyrics(currentLyrics);
        qDebug() << "Loaded existing lyrics to interface";
    } else {
        // 若未获取到歌词，显示默认提示
        QString defaultLyrics = "[00:00.00] 暂无歌词";
        lyricsInterface->loadLyrics(defaultLyrics);
        qDebug() << "Loaded default lyrics to interface";
    }

    stackedWidget->setCurrentIndex(1); // 切换到歌词界面
    qDebug() << "Switched to lyrics interface";
}
//发送歌词请求
void MusicComponent::fetchLyrics()
{
    if (currentPlayingSongId.isEmpty()) {
        qDebug() << "No song ID available for fetching lyrics";
        return;
    }

    qDebug() << "Fetching lyrics for song ID:" << currentPlayingSongId;

    // 构造歌词请求URL
    QString lyricsUrl = QString("http://music.163.com/api/song/lyric?id=%1&lv=1&kv=1&tv=-1")
                           .arg(currentPlayingSongId);

    QNetworkRequest request;
    request.setUrl(QUrl(lyricsUrl));
    request.setRawHeader("Referer", "http://music.163.com");
    request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");

    QNetworkReply *reply = manager->get(request);
    connect(reply, &QNetworkReply::finished, this, &MusicComponent::handleLyricsReply);
}
//解析歌词响应
void MusicComponent::handleLyricsReply()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (!reply) return;

    if (reply->error() == QNetworkReply::NoError) {
        QByteArray data = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(data);
        if (!doc.isNull() && doc.isObject()) {
            QJsonObject rootObj = doc.object();

            QString lyricsText = "";

            // 优先获取逐字歌词（lyric），如果没有则获取普通歌词（lrc）
            if (rootObj.contains("lrc") && rootObj["lrc"].isObject()) {
                QJsonObject lrcObj = rootObj["lrc"].toObject();
                lyricsText = lrcObj["lyric"].toString();
                qDebug() << "Got lrc lyrics, length:" << lyricsText.length();
            }

            // 如果逐字歌词为空，尝试获取翻译歌词
            if (lyricsText.isEmpty() && rootObj.contains("tlyric") && rootObj["tlyric"].isObject()) {
                QJsonObject tlyricObj = rootObj["tlyric"].toObject();
                lyricsText = tlyricObj["lyric"].toString();
                qDebug() << "Got tlyric lyrics, length:" << lyricsText.length();
            }

            // 如果还是没有歌词，使用纯文本歌词
            if (lyricsText.isEmpty() && rootObj.contains("txt") && rootObj["txt"].isString()) {
                lyricsText = rootObj["txt"].toString();
                qDebug() << "Got txt lyrics, length:" << lyricsText.length();
            }

            currentLyrics = lyricsText;

            // 立即更新歌词界面（如果正在显示）
            if (stackedWidget->currentIndex() == 1 && lyricsInterface) {
                lyricsInterface->loadLyrics(currentLyrics);
                qDebug() << "Updated lyrics interface with new lyrics";
            }

            qDebug() << "Lyrics fetched successfully for song:" << currentPlayingSongId;
        } else {
            qDebug() << "Failed to parse JSON response";
            currentLyrics = "[00:00.00] 暂无歌词";
        }
    } else {
        qDebug() << "获取歌词失败：" << reply->errorString();
        currentLyrics = "[00:00.00] 暂无歌词";
    }
    reply->deleteLater();
}
// 返回主界面
void MusicComponent::backToMainInterface()
{
    stackedWidget->setCurrentIndex(0); // 切换回主界面
}
void MusicComponent::resetSongListInterface()
{
    qDebug() << "Resetting song list interface state";

    // 确保隐藏
    songListInterface->hide();

    // 确保父对象正确
    if (songListInterface->parent() != this) {
        songListInterface->setParent(this);
        qDebug() << "Reset parent to MusicComponent";
    }

    // 确保widget_2显示正确的控件
    ui->listWidget_2->setVisible(true);
    ui->pushButton_4->setVisible(true);
    ui->pushButton_5->setVisible(true);
    ui->lineEdit_2->setVisible(true);
}
void MusicComponent::debugUIState()
{
    qDebug() << "=== UI State Debug ===";
    qDebug() << "Stacked widget index:" << stackedWidget->currentIndex();
    qDebug() << "Widget_2 visible:" << ui->widget_2->isVisible();
    qDebug() << "Song list interface visible:" << songListInterface->isVisible();
    qDebug() << "Song list interface parent:" << songListInterface->parent();
    qDebug() << "Current playlist:" << currentPlaylist;
    qDebug() << "======================";
}
// 加载默认歌单（我的收藏）
void MusicComponent::loadDefaultPlaylist()
{
    defaultPlaylistSongs.clear();

    QString filePath = "playlists/我的收藏.txt";
    QFile file(filePath);

    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        while (!in.atEnd()) {
            QString line = in.readLine().trimmed();
            if (!line.isEmpty()) {
                defaultPlaylistSongs.append(line);
            }
        }
        file.close();
        qDebug() << "Loaded default playlist with" << defaultPlaylistSongs.size() << "songs";
    }
}

// 处理上一首请求
void MusicComponent::onPreviousSongRequested()
{
    if (isDefaultPlaylistMode && !defaultPlaylistSongs.isEmpty()) {
        // 在默认歌单中播放上一首
        currentPlayIndex = (currentPlayIndex - 1 + defaultPlaylistSongs.size()) % defaultPlaylistSongs.size();
        playSongFromDefaultPlaylist();
    } else if (!searchResultIds.isEmpty()) {
        // 在搜索结果中播放上一首
        currentSearchIndex = (currentSearchIndex - 1 + searchResultIds.size()) % searchResultIds.size();
        selectedSongId = searchResultIds[currentSearchIndex];
        playMusic();
    }
}

// 处理下一首请求
void MusicComponent::onNextSongRequested()
{
    if (isDefaultPlaylistMode && !defaultPlaylistSongs.isEmpty()) {
        // 在默认歌单中播放下一首
        currentPlayIndex = (currentPlayIndex + 1) % defaultPlaylistSongs.size();
        playSongFromDefaultPlaylist();
    } else if (!searchResultIds.isEmpty()) {
        // 在搜索结果中播放下一首
        currentSearchIndex = (currentSearchIndex + 1) % searchResultIds.size();
        selectedSongId = searchResultIds[currentSearchIndex];
        playMusic();
    } else {
        // 如果没有搜索结果，切换到默认歌单播放
        switchToDefaultPlaylistMode();
    }
}

// 从默认歌单播放歌曲
void MusicComponent::playSongFromDefaultPlaylist()
{
    if (currentPlayIndex < 0 || currentPlayIndex >= defaultPlaylistSongs.size()) {
        return;
    }

    QString songLine = defaultPlaylistSongs[currentPlayIndex];
    QStringList parts = songLine.split('|');

    if (parts.size() >= 2) {
        selectedSongId = parts[1]; // 歌曲ID
        currentPlayingSongId = selectedSongId;
        playMusic();
    }
}

// 切换到默认歌单模式
void MusicComponent::switchToDefaultPlaylistMode()
{
    loadDefaultPlaylist();
    if (!defaultPlaylistSongs.isEmpty()) {
        isDefaultPlaylistMode = true;
        currentPlayIndex = 0;
        playSongFromDefaultPlaylist();
    }
}

// 处理媒体状态变化
void MusicComponent::onMediaStatusChanged(QMediaPlayer::MediaStatus status)
{
    if (status == QMediaPlayer::EndOfMedia) {
        // 歌曲播放结束，自动播放下一首
        qDebug() << "Song finished, playing next song automatically";
        onNextSongRequested();
    }
}
